<template>
  <div class="StepperPhoto">
    <el-button @click="getSong()">
      随机获取歌曲
    </el-button>
    <el-button @click="save('kk')" :disabled="isDisabled">
      保存
    </el-button>
    <div>歌曲名称:{{obj.songName}}</div>
    <div>歌曲作者:{{obj.useName}}</div>
    <div>图片链接:<a :href="obj.names">{{obj.names}}</a></div>
    <div>歌曲链接:<a :href="obj.name">{{obj.name}}</a></div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      isDisabled: false,
      obj: {
        songName: "",
        useName: "",
        names: "",
        name: "",
      },
      intervalId: null,
    }
  },
  watch:{
    obj(news, old){
      this.save(news)
    }
  },
  created() {
    // 设置定时器，每5秒刷新一次数据
    this.intervalId = setInterval(this.getSong, 7000);
  },
  destroyed() {
    // 清除定时器
    if (this.intervalId) {
      clearInterval(this.intervalId);
    }
  },
  methods:{
    enables(){
      setTimeout(() =>{
        this.isDisabled = false
      },1500)
    },
    getSong () {
      axios({
        url: 'https://api.vvhan.com/api/wyMusic/%E6%96%B0%E6%AD%8C%E6%A6%9C?type=json',
        method: 'get',
      }).then(res => {
        //成功回调
        this.obj = {
          songName: res.data.info.name,
          useName: res.data.info.auther,
          names: res.data.info.pic_url,
          name: res.data.info.url,
        }
      })
    },
    save(res){
      if (this.obj.name === '') {
        return false
      }
      this.isDisabled = true
      this.enables()
      if (res === 'kk') {
        console.log('点击保存')
        this.$axios.post("/wyysong/save", this.obj).then((res) => {
          if (res.data.code == 200) {
            this.$notify({
              title: '成功',
              message: res.data.message,
              type: 'success'
            });
          }
        })
      } else {
        console.log('自动保存')
        this.$axios.post("/wyysong/save", res).then((res) => {
          console.log(res.data.message)
          if (res.data.code == 200) {
            this.$notify({
              title: res.data.data,
              message: res.data.message,
              type: res.data.data === "成功" ? 'success' : 'error'
            });
          }
        })
      }
    },
  },
}
</script>

<style scoped>
.StepperPhoto {
  width: 100%;
}
</style>
